package util;

import java.util.List;

import models.CNAverage;
import models.SensorData;
import play.Logger;
import play.db.jpa.JPA;
import play.db.jpa.JPABase;
import play.db.jpa.Model;
import play.jobs.Every;
import play.jobs.Job;

public class DBCleanUpJob extends Job {

    private static final long REMAINING_VALUES = 10;

    @Override
    public void doJob() throws Exception {
        cleanupSensorData();
        cleanupCNAverages();
    }

    private void cleanupCNAverages() {
        List<CNAverage> obsoleteAverages = CNAverage.getObsoleteCNA(REMAINING_VALUES);
        Logger.info("Deleting %s obsoleteCNAverages", obsoleteAverages.size());
        for (CNAverage cnAverage : obsoleteAverages) {
            new DeleteCNAJob(cnAverage.getId()).now();
        }
        Logger.info("Deleting obsoleteCNAverages finished");
    }

    private void cleanupSensorData() {
        List<SensorData> obsoleteSensorDatas = SensorData.getObsoleteSensorDatas(REMAINING_VALUES);
        Logger.info("Deleting %s obsoleteSensorData", obsoleteSensorDatas.size());
        for (SensorData sensorData : obsoleteSensorDatas) {
            new DeleteSensorDateJob(sensorData.getId()).now();
        }
        Logger.info("Deleting obsoleteSensorData finished");

    }

    private class DeleteCNAJob extends Job {

        private long id;

        private DeleteCNAJob(long id) {
            this.id = id;
        }

        @Override
        public void doJob() throws Exception {
            CNAverage cna = CNAverage.findById(id);
            if (cna != null) {
                cna.delete();
            }
        }
    }

    private class DeleteSensorDateJob extends Job {

        private long id;

        private DeleteSensorDateJob(long id) {
            this.id = id;
        }

        @Override
        public void doJob() throws Exception {
            SensorData sd = SensorData.findById(id);
            if (sd != null) {
                sd.delete();
            }
        }
    }
}
